import {
  userPasswordLoginApi,
  userCodeLoginApi,
  getCodeApi,
  bindUserQQAndMobileApi,
  userLoginByQQApi
} from '@/services/user'

import { ref, onUnmounted } from 'vue'

import { useUserStore } from '@/stores'

import { showSuccessToast } from 'vant'

import type { FormInstance } from 'vant'

import type { LoginForm, GetCodeForm, BindForm } from '@/types/user'

const userStore = useUserStore()

function login(
  routerCallback: () => void,
  otherCallback?: (is: string) => void
) {
  const mobile = ref('')
  const password = ref('')
  const code = ref('')

  const time = ref(0)

  let timerId: number

  const loginFormRef = ref<FormInstance>()

  async function getCode() {
    if (time.value) return
    try {
      await loginFormRef.value!.validate('mobile')
      codeThrottle()
      const form: GetCodeForm = {
        mobile: mobile.value,
        type: 'login'
      }

      await getCodeApi(form)
      showSuccessToast('发送验证码成功')
    } catch (error) {
      console.log(error)
    }
  }

  function codeThrottle() {
    timerId && clearInterval(timerId)
    time.value = 60
    timerId = setInterval(() => {
      if (!time.value) {
        clearInterval(timerId)
      }
      time.value -= 1
    }, 1000)
  }

  async function onUserLogin(
    type: 'codeLogin' | 'passLogin' | 'qqLogin' | 'bindUser',
    form: LoginForm | string | BindForm
  ) {
    try {
      let data

      if (type === 'codeLogin') {
        const res = await userCodeLoginApi(form as LoginForm)
        data = res.data
      }
      if (type === 'passLogin') {
        const res = await userPasswordLoginApi(form as LoginForm)
        data = res.data
      }

      if (type === 'qqLogin') {
        const res = await userLoginByQQApi(form as string)
        data = res.data
      }

      if (type === 'bindUser') {
        const res = await bindUserQQAndMobileApi(form as BindForm)
        data = res.data
      }
      if (!data) return
      userStore.setUser(data)
      showSuccessToast({
        type: 'success',
        message: '登录成功'
      })

      setTimeout(() => {
        routerCallback()
      }, 1000)
    } catch (error) {
      if (type === 'qqLogin') {
        otherCallback && otherCallback(form as string)
      }
    }
  }

  onUnmounted(() => {
    timerId && clearInterval(timerId)
  })

  return {
    time,
    loginFormRef,
    mobile,
    password,
    code,
    getCode,
    onUserLogin
  }
}

export default login
